﻿using System;
using System.Web.UI;
using WeChat.Common;
using BLL;
using WeChat.Common2;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections.Generic;
using WeChat.JsSDK.lib;
using System.Data;

namespace WeChat.JsSDK.WxPay
{
    public partial class ResultNotifyPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session.Clear();
                notice_url();
            }
        }
        //支付回调页面
        public void notice_url()
        {
            SortedDictionary<string, object> results = getPostStr();
            //string openid = results["openid"].ToString(); ApplicationLog.Write("openid解析:" + openid);
            //string Opid =  results["Opid"].ToString();
            ApplicationLog.Write("---------------------进入充值--------------------");
            if (results.ContainsKey("result_code") && results["result_code"].ToString() == "SUCCESS")
            {
                //验证签名，判断接收信息是否合法
                string getSign = results["sign"].ToString();
                string sign = WxPayApi.toSign(results);
                if (!getSign.Equals(sign))
                {
                    ApplicationLog.Write("接收到非法信息！");
                    return;
                }
                string out_trade_no = results["out_trade_no"].ToString();//商户订单号
                string Opids = ReBLL.ObtainOpid(out_trade_no);
                string time = DateTime.ParseExact(results["time_end"].ToString(), "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");
                ApplicationLog.Write("time解析:" + time);
                ApplicationLog.Write("trade_type:" + results["trade_type"].ToString());
                //=================公众号充值，将微信支付记录同步至数据库=====================

                //if (results["trade_type"] != null && results["trade_type"].ToString() == "JSAPI" && !WxPayAddBLL.isExistRecord(Opids, time))
                if (results["trade_type"] != null && results["trade_type"].ToString() == "JSAPI" && !WxPayAddBLL.isExistRecord(Opids, time, out_trade_no))
                {
                    try
                    {
                        double money = Double.Parse(results["total_fee"].ToString()) / 100;
                        if (results["attach"].ToString() == "addmoney")
                        {
                            string time1 = DateTime.ParseExact(results["time_end"].ToString(), "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");//获取交易支付成功时间
                          
                            ApplicationLog.Write("JSAPI参数：" + "out_trade_no:" + out_trade_no + "time:" + time1 + "money:" + money + "Opids:" + Opids);
                            ReBLL.OrderNum1(out_trade_no, time1, 1);
                            int i = WxPayAddBLL.PayAdd(Opids, money, time1);
                            if (i > 0)
                            {
                                //返回微信服务器接收通知结果
                                Response.Write(getRetrunXml("SUCCESS", "OK"));
                                ApplicationLog.Write("JSAPI：成功充值");
                            }


                        }
                        else
                        {
                            MenuReservationBLL mb = new MenuReservationBLL();                         
                            mb.updateOrderList3(DateTime.Now.ToString(), "微信支付", out_trade_no, "","");
                            mb.reservation(out_trade_no, money.ToString(), DateTime.Now.ToString());
                            Response.Write(getRetrunXml("SUCCESS", "OK"));
                            ApplicationLog.Write("JSAPI：订餐成功");
                        }




                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Write("插入失败：" + ex.Message);
                        Response.Write(getRetrunXml("SUCCESS", "failed"));
                        throw;
                    }
                }
                else if (results["trade_type"] != null && results["trade_type"].ToString() == "NATIVE")
                {
                    //=================扫码充值，将微信支付记录同步至数据库，不更新余额=====================
                    try
                    {
                        out_trade_no = results["out_trade_no"].ToString();//商户订单号
                        string cardno = results["attach"].ToString(); //用户卡号
                        string is_subscribe = results.ContainsKey("is_subscribe") ? results["is_subscribe"].ToString() : "";//是否关注
                        string trade_type = results["trade_type"].ToString();//支付类型
                        string total_fee = (Double.Parse(results["total_fee"].ToString()) / 100).ToString();//支付金额
                        string transaction_id = results["transaction_id"].ToString();//微信支付订单号
                                                                                     //string endTime = results["time_end"].ToString();//支付完成时间
                                                                                     //ApplicationLog.Write("解析值out_trade_no:" + out_trade_no + ";cardno:" + cardno + ";is_subscribe:" + is_subscribe + ";trade_type:" + trade_type + ";total_fee:" + total_fee + ";transaction_id:" + transaction_id + ";endTime:" + time);

                        //int i = WxPayAddBLL.addNativeRecord(out_trade_no, cardno, openid, is_subscribe, trade_type, total_fee, transaction_id, time);
                        //if (i > 0)
                        //{
                        //    //返回微信服务器接收通知结果
                        //    Response.Write(getRetrunXml("SUCCESS", "OK"));
                        //}
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Write("插入失败：" + ex.Message);
                        Response.Write(getRetrunXml("SUCCESS", "failed"));
                        throw;
                    }
                }
                else if (results["trade_type"] != null && results["trade_type"].ToString() == "MWEB" && !WxPayAddBLL.isExistRecord(Opids, time, out_trade_no))
                {
                    try
                    {

                        out_trade_no = results["out_trade_no"].ToString();//商户订单号
                        Opids = ReBLL.ObtainOpid(out_trade_no);
                        string time1 = DateTime.ParseExact(results["time_end"].ToString(), "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");//获取交易支付成功时间
                        double money = Double.Parse(results["total_fee"].ToString()) / 100;
                        ApplicationLog.Write("H5参数：" + "out_trade_no:" + out_trade_no + "time:" + time1 + "money:" + money + "Opids:" + Opids);
                        ReBLL.OrderNum1(out_trade_no, time1, 1);
                        int i = WxPayAddBLL.PayAdd(Opids, money, time1);
                        if (i > 0)
                        {
                            //返回微信服务器接收通知结果
                            Response.Write(getRetrunXml("SUCCESS", "OK"));
                            ApplicationLog.Write("MWEB：成功充值");
                        }
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Write("插入失败：" + ex.Message);
                        Response.Write(getRetrunXml("SUCCESS", "failed"));
                        throw;
                    }
                }
            }
            else
            {
                ApplicationLog.Write("支付回调页面业务代码区：交易失败。");
                Response.Write(getRetrunXml("SUCCESS", "failed"));
            }
        }

        /// <summary>
        /// 接收微信服务器发送的xml数据
        /// </summary>
        /// <returns></returns>
        public SortedDictionary<string, object> getPostStr()
        {
            Stream stream = Request.InputStream;
            int len = (int)stream.Length;
            byte[] inputbytes = new byte[len];
            stream.Read(inputbytes, 0, len);
            stream.Close();
            string data = Encoding.GetEncoding("utf-8").GetString(inputbytes);
            ApplicationLog.Write("----------------【回调地址接收数据】-----------------");
            ApplicationLog.Write("回调地址接收到的xml:" + data);
           
            //将接收到的数据转换为xml类型格式
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(data);
            XmlNodeList xml = doc.DocumentElement.ChildNodes;
            return exChangeXml(xml);
        }

        //生成返回xml消息
        public string getRetrunXml(string return_codes, string return_msgs)
        {
            XmlDocument xd = new XmlDocument();
            XmlElement first = xd.CreateElement("xml");
            xd.AppendChild(first);
            XmlElement return_code = xd.CreateElement("return_code");
            return_code.AppendChild(xd.CreateCDataSection(return_codes));
            first.AppendChild(return_code);
            XmlElement return_msg = xd.CreateElement("return_msg");
            return_msg.AppendChild(xd.CreateCDataSection(return_msgs));
            first.AppendChild(return_msg);
            return xd.InnerXml;
        }

        //将xml转换成字典类型
        public SortedDictionary<string, object> exChangeXml(XmlNodeList xml)
        {
            SortedDictionary<string, object> sd = new SortedDictionary<string, object>();
            foreach (XmlNode xn in xml)
            {
                sd.Add(xn.Name, xn.InnerText);
            }
            return sd;
        }
    }
}